package com.ruoyi.common.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Repeatable 过滤器
 * 
 * @author ruoyi
 */
public class RepeatableFilter implements Filter
{
    private static final Logger log = LoggerFactory.getLogger(RepeatableFilter.class);
    private static final String EXCLUDED_PATH = "/site/stripe/webhook";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String requestURI = httpServletRequest.getRequestURI();

            // 如果请求 URI 包含排除路径，则直接放行，不进行任何包装。
            if (StringUtils.containsIgnoreCase(requestURI, EXCLUDED_PATH)) {
                log.info("【RepeatableFilter】Webhook 路径 {} 匹配排除规则 {}。跳过包装。", requestURI, EXCLUDED_PATH);
                // 直接交给下一个过滤器或目标 Controller，使用原始的 request 对象
                chain.doFilter(request, response);
                return;
            }
            else {
                // 如果是其他路径，可以打印一条 DEBUG 级别的日志
                log.debug("【RepeatableFilter】普通路径 {} 未匹配排除规则。", requestURI);
            }
        }

        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest
                && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE))
        {
            requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
        }
        if (null == requestWrapper)
        {
            chain.doFilter(request, response);
        }
        else
        {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy()
    {

    }
}
